package cn.edu.svtcc.controller;

import cn.edu.svtcc.config.StudentConfig;
import cn.edu.svtcc.domain.Grade;
import cn.edu.svtcc.domain.Result;
import cn.edu.svtcc.util.PropertiesSaver;
import org.springframework.web.bind.annotation.*;
import java.util.List;
import java.util.concurrent.atomic.AtomicInteger;
import java.util.stream.Collectors;

@RestController
public class GradeController {
    private final StudentConfig studentConfig;
    private final AtomicInteger gradeIdCounter;

    public GradeController(StudentConfig studentConfig) {
        this.studentConfig = studentConfig;
        // 初始化 gradeIdCounter，从现有最大ID开始
        int maxId = studentConfig.getGrades().getList().stream()
                .mapToInt(g -> Integer.parseInt(g.getGradeID()))
                .max().orElse(0);
        this.gradeIdCounter = new AtomicInteger(maxId);
    }

    @GetMapping("/api/students/{number}/grades")
    public Result getGradesByStudent(@PathVariable String number) {
        // 验证学生是否存在
        boolean studentExists = studentConfig.getList().stream()
                .anyMatch(s -> s.getNumber().equals(number));
        if (!studentExists) {
            return Result.error(404, "学生不存在");
        }

        // 获取该学生的所有成绩 getStudentNumber
        List<Grade> studentGrades =  studentConfig.getGrades().getList().stream()
                .filter(g -> g.getStudentNumber().equals(number))
                .collect(Collectors.toList()); // 替换为 collect

        return Result.success(studentGrades);
    }

    @PostMapping("/api/students/{number}/grades")
    public Result createGrade(
            @PathVariable String number,
            @RequestBody Grade gradeRequest
    ) throws Exception {
        // 验证学生是否存在
        boolean studentExists = studentConfig.getList().stream()
                .anyMatch(s -> s.getNumber().equals(number));
        if (!studentExists) {
            return Result.error(404, "学生不存在");
        }

        // 生成唯一 gradeID
        String newGradeId = String.valueOf(gradeIdCounter.incrementAndGet());
        Grade newGrade = new Grade();
        newGrade.setGradeID(newGradeId);
        newGrade.setStudentNumber(number);
        newGrade.setCourse(gradeRequest.getCourse());
        newGrade.setScore(gradeRequest.getScore());

        // 保存到配置
        studentConfig.getGrades().getList().add(newGrade);
        PropertiesSaver.saveAllData(studentConfig.getList(), studentConfig.getGrades().getList());

        return Result.success(201, "create", newGrade);
    }

    @PutMapping("/api/grades/{gradeID}")
    public Result updateGrade(
            @PathVariable String gradeID,
            @RequestBody Grade updatedGrade
    ) throws Exception {
        for (Grade grade : studentConfig.getGrades().getList()) {
            if (grade.getGradeID().equals(gradeID)) {
                // 更新课程和分数（保留关联的学生学号）
                grade.setCourse(updatedGrade.getCourse());
                grade.setScore(updatedGrade.getScore());

                PropertiesSaver.saveAllData(studentConfig.getList(), studentConfig.getGrades().getList());
                return Result.success(200, "OK", grade);
            }
        }
        return Result.error(404, "成绩记录不存在");
    }

    @DeleteMapping("/api/grades/{gradeID}")
    public Result deleteGrade(@PathVariable String gradeID) throws Exception {
        Grade removedGrade = null;
        for (int i = 0; i < studentConfig.getGrades().getList().size(); i++) {
            if (studentConfig.getGrades().getList().get(i).getGradeID().equals(gradeID)) {
                removedGrade = studentConfig.getGrades().getList().remove(i);
                break;
            }
        }

        if (removedGrade != null) {
            PropertiesSaver.saveAllData(studentConfig.getList(), studentConfig.getGrades().getList());
            return Result.success(200, "删除完成", removedGrade);
        } else {
            return Result.error(404, "成绩记录不存在");
        }
    }
}